﻿using System.Collections.Generic;
using System.Collections.Specialized;
using Google.Apis.Translate.v2;
using Google.Apis.Translate.v2.Data;
using LanguagesResource = Google.Apis.Translate.v2.LanguagesResource;
using TranslationsResource = Google.Apis.Translate.v2.Data.TranslationsResource;

namespace Google.Translates.Core
{
    public class TranslatorByGoogleLib : TranslatorByGoogle
    {
        public TranslatorByGoogleLib()
        {
            
        }

        public TranslatorByGoogleLib(int appIdIndex)
        {
            
        }

        public override object GetTranslations(List<string> shotSentence, string srcLangKey, string trgLangKey)
        {
            TranslationsListResponse reObj = null;
            var service = new TranslateService {Key = m_AppId};
            var scTemp = new StringCollection();
            int chAmount = 0;
            for (int i = 0; i < shotSentence.Count; i++)
            {
                string srcWords = shotSentence[i];
                srcWords = srcWords.Trim();
                if (string.IsNullOrEmpty(srcWords)) continue;
                scTemp.Add(srcWords);
                chAmount += srcWords.Length;
                if (chAmount > 1000 || i == (shotSentence.Count - 1))
                {
                    var ss = new string[scTemp.Count];
                    for (int k = 0; k < scTemp.Count; k++)
                    {
                        ss[k] = scTemp[k];
                    }
                    TranslationsListResponse tempEachVal = service.Translations.List(ss, trgLangKey).Fetch();
                    if (reObj == null)
                        reObj = tempEachVal;
                    else
                    {
                        foreach (TranslationsResource tran in tempEachVal.Translations)
                        {
                            reObj.Translations.Add(tran);
                        }
                    }
                    scTemp.Clear();
                }
            }
            return reObj;
        }

        //https://www.googleapis.com/language/translate/v2/detect?key=INSERT-YOUR-KEY&q=google+translate+is+fast
        public DetectionsListResponse DetectTheSentence(string sentenceVal)
        {
            if (string.IsNullOrEmpty(sentenceVal.Trim())) return null;
            var service = new TranslateService {Key = m_AppId};
            return service.Detections.List(sentenceVal.Trim()).Fetch();
        }

        //https://www.googleapis.com/language/translate/v2/languages?key=INSERT-YOUR-KEY&target=zh-TW
        public LanguagesListResponse GetLanguageInfos(string trgLangKey)
        {
            var service = new TranslateService {Key = m_AppId};
            LanguagesResource.ListRequest op = service.Languages.List();
            if (string.IsNullOrEmpty(trgLangKey))
                op.Target = trgLangKey;
            return op.Fetch();
        }
    }
}